﻿using Core.Framework;
using iTool.ClusterComponent;
using iTool.PluginCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;

namespace Silo.CloudService
{
    public class PluginsHttpHostHandel
    {
        public static IHost Create()
        {
            Print.Staring("\niTool> Create plugins http hosting, http://*:17010.");

            IHost host = new HostBuilder()
                .ConfigureAppConfiguration(config =>
                {
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                })
                .ConfigureWebHostDefaults(host =>
                {
                    host.UseStartup<Startup>();
                    host.UseUrls($"http://*:17010");
                })
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.SetBasePath(Directory.GetCurrentDirectory());
                })
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<LifetimeEventsHostedService>();
                })
                .Build();

            var task = host.RunAsync();

            task.Wait(2000);

            return host;
        }
    }


    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    });
            });

            var collection = ProviderOfServices.GetServiceCollection("PluginsProvider");
            collection.AddSingleton(Configuration);

            services.AddSingleton(Configuration);
            services.AddSingleton<ServerPluginsManager>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors("AllowAll");
            app.UseMiddleware<PluginsProxyMiddleware>();
        }
    }
}
